package main.singleton;

/**
 * @Author: SerMs
 * @Date: 2024/06/17 17 19
 * @Email: 1839928782@qq.com
 * @Blog: https://serms.top
 **/
public class Singleton05 {
    private static Singleton05 INSTANCE;

    private Singleton05() {
    }

    private static Singleton05 getInstance() {
        if (INSTANCE == null) {
            // 这里加锁的时候还是会导致线程不安全的问题,原因在于多个线程进来的时候判断INSTANCE不为空,
            // 就会拿锁,如果多个线程都在抢同一把锁就会等待 前面一个释放锁后就拿锁在new对象,就导致不同对象了
            synchronized (Singleton05.class) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                INSTANCE = new Singleton05();
            }
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            // 多线程
            new Thread(() -> System.out.println(Singleton05.getInstance().hashCode())).start();
        }
    }
}
